package cn.shadow.thread;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * 只能有一个条件等待队列，是java  wait/notify机制的局限性。
 * @param <T>
 */
public class MyBlockingQueue<T> {

    private Queue<T> queue;
    private int limit;
    public MyBlockingQueue(int limit) {
        this.queue = new ArrayDeque<>(limit);
        this.limit=limit;
    }


    public synchronized void put(T t) throws InterruptedException {
        if (queue.size() == limit) {
            wait();
        }
        queue.add(t);
        System.out.println("size="+queue.size());
        notifyAll();
    }

    public synchronized T take() throws InterruptedException {
        if (queue.isEmpty()) {
            wait();
        }
        T peek = queue.poll();
        notifyAll();
        return peek;
    }

    public static void main(String[] args) {
        MyBlockingQueue<Integer> queue = new MyBlockingQueue<>(2);

        new Thread(()->{
                while (true){
                    try {
                        queue.put(100);
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


        }).start();
        new Thread(()->{
            while (true){
                try {
                    Integer take = queue.take();
                    System.out.println(take);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }

}
